﻿using Word = Microsoft.Office.Interop.Word;
using MyWordAddIn.socket;
using System;
using System.ComponentModel;
using System.Windows.Forms;
using MyWordAddIn.Tool;

namespace MyWordAddIn
{
    public partial class SendFile : Form
    {

        private bool status;

        private SocketClient client;

        private string FileName;

       // private BackgroundWorker bw;

        public int fd;


        ~SendFile()
        {
            this.client.Close();
        }


        protected override void WndProc(ref Message m)
        {
            //Console.WriteLine(m.Msg);
            const int WM_SYSCOMMAND = 0x0112;
            const int SC_CLOSE = 0xF060;
            if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == SC_CLOSE)
            {
                //捕捉关闭窗体消息      
                //用户点击关闭窗体控制按钮   注释为最小化窗体   
                //this.WindowState = FormWindowState.Minimized;
               // bw.Dispose();

               
                // 关闭 tcp链接
                this.client.Close();

                //窗体隐藏
                this.Close();
                return;
            }
            base.WndProc(ref m);
        }

        public SendFile()
        {

            string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + "word.ini";

            ReadFile instance = ReadFile.getInstance(path);

            string ip;

            bool res = instance.getDataByKey("ip", out ip);

            if (!res)
            {
                throw new Exception("找不到" + path + "配置文件");
            }

            string port;

            instance.getDataByKey("port", out port);

            this.client = new SocketClient(ip, ushort.Parse(port));

            try
            {
                client.connect();

               
            }
            catch (Exception)
            {

            }
            InitializeComponent();


            ListBox.CheckForIllegalCrossThreadCalls = false;

            this.client.box = listBoxOnline;
           

        }

        private void MethodToDoWork(object sen, DoWorkEventArgs e)
        {
            while(this.client.packets.Count == 0)
            {

            }

            foreach (Packet packer in this.client.packets)
            {
                listBoxOnline.BeginInvoke((Action)
                    (() => listBoxOnline.Items.Add(packer.fd + ":" + packer.userName)));
            }
        }



        private void formLoad(object sender, EventArgs e)
        {
            try
            {
                
            } catch
            {

            }
            

            // eventHandler(this, e);

            //bw = new BackgroundWorker();

            //bw.DoWork += MethodToDoWork;

            //bw.RunWorkerAsync();
        }

        /**
         * 列表选中
         */
        private void SelectedValueChanged(object sender, EventArgs e)
        {

            ListBox data = sender as ListBox;

            string resString = data.SelectedItem.ToString();

            if (resString == null || 0 == resString.Length)
            {
                return;
            }

            string[] res = resString.Split(':');


            fd = int.Parse(res[0]);

            //Console.WriteLine(sender);
        }

        private void label3_Click(object sender, EventArgs e)
        {

        }

        private void SendClick(object sender, EventArgs e)
        {
            if (0 == fd)
            {
                MessageBox.Show("请选择要发送的用户");
                return;
            }

            if (this.radioButtonY.Checked)
            {
                this.sendCurrentFile(this.FileName);
            }
            else
            {
                this.SendFileData(this.FileName);
            }

           
        }

        public void sendCurrentFile(string file)
        {

            if (null == this.fileNameBox.Text || 0 == this.fileNameBox.Text.Length)
            {
                MessageBox.Show("请输入名字");
                return;
            }

            Word.Document document = Globals.ThisAddIn.Application.ActiveDocument;

            string txt = document.Content.Text;

            Environment.CurrentDirectory = Environment.GetEnvironmentVariable("TEMP");


            string fileName = Environment.CurrentDirectory  + "\\" +this.fileNameBox.Text + ".docx";

            Word.Document openDoc =   Globals.ThisAddIn.Application.Documents.Add();


            openDoc.Content.Text = txt;

            openDoc.SaveAs(fileName);

            openDoc.Close();

            int flag = this.client.registerSendFile(fileName, fd);

            if (0 == flag)
            {
                MessageBox.Show("发送成功");

                // this.Dispose();
            }

        }


        private void buttonSelectFileClick(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Word文件(*.doc;*.docx)|*.doc;*.docx|所有文件|*.*";
            ofd.ValidateNames = true;
            ofd.CheckPathExists = true;
            ofd.CheckFileExists = true;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                this.FileName = ofd.FileName;

                this.fileField.Text = this.FileName;


                ofd.Dispose();

            }

            
        }

        // 发送当前文件
        private void SendFileData(string FileName)
        {

            //this.listBoxOnline.Items[this.listBoxOnline.SelectedIndex].;

            int flag = this.client.registerSendFile(FileName, fd);

            if (0 ==flag)
            {
                MessageBox.Show("发送成功");

               // this.Dispose();
            }

        }

        private void radioButtonY_CheckedChanged(object sender, EventArgs e)
        {
            this.status = this.radioButtonY.Checked;

            this.setOpenSelectFile(false);

            this.setOpenSelectFileName(true);

        }

        private void radioButtonN_CheckedChanged(object sender, EventArgs e)
        {
            this.status = this.radioButtonN.Checked;

            this.setOpenSelectFile(true);

            this.setOpenSelectFileName(false);


        }

        private void setOpenSelectFile( bool status)
        {
            this.label1.Visible = status;

            this.fileField.Visible = status;

            this.buttonSelectFile.Visible = status;

        }


        private void setOpenSelectFileName(bool status)
        {
            this.fileNameLabel.Visible = status;

            this.fileNameBox.Visible = status;
        }
    }
}
